using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;

public class FinalDecisionScreen : MonoBehaviour {

	
	public int m_numSections;
        public int[] m_sectionLength;
        public int[] m_maxAnswers;
        public int sectionCounter;
        public int currentAnswer;
	private string[,] m_answers;
        private string[] m_question;
	
	
    string[,] answers;
    bool[] toggles;
    string[] feedback;
    bool showFeedback = false;
    System.DateTime startTime;
    int timeLimit;
    System.DateTime finishTime;
	int numSections;
	public GUIStyle toggleStyle;
	public GUIStyle loggedInStyle;
	public GUIStyle fDStyle;
	public GUIStyle nextButtonStyle;
	public GUIStyle labelStyle;
	public GUITexture topBar;
	public Texture finalDecisionTex;
	string userName = "";
	Rect wRect = new Rect(Screen.width/2-455,Screen.height/2-250,910,500);
	public GUISkin fdSkin;
	int[] points;
	int[] maxAnswers;
	string allFeedback = "";
	Vector2 feedbackScrollPosition = new Vector2(0,0);
	public GUIStyle blankStyle;
	public Texture logo;

	// Use this for initialization
	void Start () {
		PrivateInit();
		topBar.pixelInset = new Rect(-512, Screen.height/2-30, 1024, 30);
        GetListOfAnswers(out answers);
		//GetFinalChoiceAnswerList("1", out answers);
        toggles = new bool[answers.Length];
        startTime = System.DateTime.Now;//XXX: sDemo only. should be this: askQuestion.GetInitTime();
        timeLimit = GetTimeLimit();
        finishTime = startTime.AddMinutes(timeLimit);
	}

    void OnGUI()
    {
		GUI.Button(new Rect(0, 50, 160, 45), logo, blankStyle);
		GUI.skin = fdSkin;
		GUI.Button(new Rect(Screen.width/2-330, 0, 119, 30), finalDecisionTex, fDStyle);
		GUI.Label(new Rect(Screen.width/2+100, 0, 167, 34), userName+" is logged in", loggedInStyle);
		System.TimeSpan temp = finishTime-System.DateTime.Now;
		string secs = temp.Seconds.ToString();
		if(temp.Seconds < 10){
			secs = "0"+temp.Seconds.ToString();
		}
        GUI.Label(new Rect(Screen.width/2+275, 0, 167, 34), "Time Remaining: "+temp.Minutes.ToString()+":"+secs, loggedInStyle);
		/*
        if (needTimer)
        {
            GUI.TextField(new Rect(600, 10, 512, 20), (finishTime - System.DateTime.Now).ToString());
        }
        */
        if (!showFeedback)
        {
            wRect = GUI.Window(0, wRect, QWindow, "");
			if (GUI.Button(new Rect(Screen.width/2+300,Screen.height-150,126,56), "", nextButtonStyle))
       		{
                List<int> finalAnswers = new List<int>();
                int counter = 0;
                for (int con = 0; con < answers.GetLength(1); con++)
                {
                    if (toggles[con])
                    {
                        finalAnswers.Add(con);
                        counter++;
                    }
                }
                if (counter > m_maxAnswers[sectionCounter])
                {
                    GUI.Label(new Rect(0,0,100,100), "Too many answers are selected.");
                }
                else
                {
                    SelectAnswer(finalAnswers, out feedback, out points);
					for (int con = 0; con < points.Length; con++)
			        {
						allFeedback += feedback[con] + "\n\n";
			        }
                    showFeedback = true;
                }
	        }
        }
		else
        {
            wRect = GUI.Window(1, wRect, FWindow, "");
			if (GUI.Button(new Rect(Screen.width/2+300,Screen.height-150,126,56), "", nextButtonStyle))
	        {
				allFeedback = "";
	            if (NextSection())
	            {
	                showFeedback = false;
					for (int con = 0; con < answers.GetLength(1); con++)
	                {
	                    if (toggles[con])
	                    {
	                        toggles[con] = false;
	                    }
	                }
	            }
	        }
        }
    }
	
	void QWindow(int id){
		GUILayout.FlexibleSpace();
		//GetMaxAnswers("1", 4, out maxAnswers);
		GUILayout.Label(sectionCounter+1 + ". " + GetQuestion() + " (Max: " + m_maxAnswers[sectionCounter] + " choices)");
		GUILayout.FlexibleSpace();
        for (int con = 0; con < answers.GetLength(1); con++)
        {
			if(answers[sectionCounter, con] != null){
				GUILayout.BeginHorizontal();
				toggles[con] = GUILayout.Toggle(toggles[con], "", toggleStyle);
	            GUILayout.Label(answers[sectionCounter, con], labelStyle);
				GUILayout.EndHorizontal();
			}
        }
		GUILayout.FlexibleSpace();
	}
	
	void FWindow(int id){
		GUILayout.FlexibleSpace();
		GUILayout.Label(sectionCounter+1 + ". " + GetQuestion());
		GUILayout.FlexibleSpace();
		feedbackScrollPosition = GUILayout.BeginScrollView(feedbackScrollPosition, labelStyle);
		GUILayout.TextArea(allFeedback);
		GUILayout.EndScrollView();
		GUILayout.FlexibleSpace();
	}
	
	bool PrivateInit()
        {
//            SaveStagePosition(InternalComponents.UserName, 4);
//            //DEBUG INFO
//            m_numSections = 1;
//            m_maxAnswers = new int[m_numSections];
//            m_maxAnswers[0] = 0;
//            m_sectionLength = new int[m_numSections];
//            m_sectionLength[0] = 0;
//
//            // 1. request the question and answers from the final stage
//            if(!DBGetQuestion(InternalComponents.m_strAvailableCaseID, out m_question))
//                return false;
//			
//			
//			
//            if (!GetListAnswers(InternalComponents.m_strAvailableCaseID, out m_answers))
//                return false;
//			
//            //NEEDS TO BE IMPLEMENTED IN THE DB
//            if (!GetNumSections(InternalComponents.m_strAvailableCaseID, out m_numSections))
//                return false;
//			
//			if (!GetMaxAnswers(InternalComponents.m_strAvailableCaseID, m_numSections, out m_maxAnswers))
//                return false;
//
//            sectionCounter = 0;
//            currentAnswer = 0;

            return true;
        }
	
	public bool GetListOfAnswers(out string[,] PossibleAnswers)
        {
           	PossibleAnswers = m_answers;
            return true;
        }
	
	public int GetTimeLimit()
        {
            int timeLimit;
            DBGetTimeLimit(out timeLimit, InternalComponents.m_strAvailableCaseID);
            return timeLimit;
        }
	
	public static bool DBGetTimeLimit(out int timeLimit, string caseID)
        {
            //Sets timeLimit to the number of minutes that the user has to complete the case. Each case has a time limit. If infinite amount of time leave as zero
            timeLimit = 0;			
			bool result = false;
			try{
				int idCase = Convert.ToInt32(caseID);
				//Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT timeLimit "+
                                      "FROM AvailableCases "+
                                      "WHERE idAvailableCases='" + idCase + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
                    if (rdr.HasRows)
                    {
						if(rdr.Read()){
							timeLimit = Convert.ToInt32(rdr[0].ToString());					
						}
						
                    }
                }
                con.Close();
			}
			catch(Exception ex){
				Console.WriteLine(ex.ToString());
				result = false;
			}
			
            return result;
        }
	
	public bool SelectAnswer(List<int> AnswerID, out string[] AnswerFeedback, out int[] Points)
        {
			Points = new int[AnswerID.Count];
            for (int con = 0; con < AnswerID.Count; con++)
            {
                // 1. Ask the system for the correct value for the answer
                int val;
				string strAns = m_answers[sectionCounter,AnswerID[con]];
                GetAnswerValue(m_question[sectionCounter], strAns, out val);
				Points[con] = val;

                // 2. Save the value in the system
                InternalComponents.m_iFinalStateScore += val;
                InternalComponents.m_iFinalChoicesMade++;
                if (val < 1)
                {
                    InternalComponents.m_iFinalChoicesFailed++;
                }
                
            }

            GetFeedback(AnswerID, out AnswerFeedback);

            // 3. Initiate a state change
            //GoToNextStage();

            return true;
        }
	
	public bool NextSection()
        {
            if (sectionCounter + 1 < m_numSections)
            {
                sectionCounter++;
                return true;
            }
            else
            {
                Application.LoadLevel(4);
                return false;
            }
        }
	
	public string GetQuestion()
        {
            return m_question[sectionCounter];
        }
	
	public static bool SaveStagePosition(string userID, int currentPosition)
        {
            // stores currentPosition as the current stage (asking questions, final decision, etc) the user is on
			// Stages in our program right now 
			/*
			 * 1. Login Screen
			 * 2. Case Selection
			 * 3. Asking Questions
			 * 4. Final Choice 
			 * 
			 * */
			
            bool result = false;

            try {
                //Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                //this has to change based on the config file that will be implemented ultimately
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con) {

                    string strQuery = "UPDATE Sessions " +
                                      "SET currentStage = @currentPosition " +
                                      "WHERE idUsers = @userID "; 
                                          
					
                    SqlCommand cmd = new SqlCommand(strQuery, con);

                    // Add external parameters to the command
                    SqlParameter param = new SqlParameter("@userID", SqlDbType.Int); // 1. Set the tipe of parameter to use
                    param.Value = Convert.ToInt32(userID);							 // 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param);										 // 3. Add the parameter to the command parameters

                    SqlParameter param2 = new SqlParameter("@currentPosition", SqlDbType.Int); // 1. Set the tipe of parameter to use
                    param2.Value = currentPosition;							 // 2. Set the value of the parameter to use
                    cmd.Parameters.Add(param2);										 // 3. Add the parameter to the command parameters


                    int iRowAffected = cmd.ExecuteNonQuery();
                    if (iRowAffected > 0) {
                        result = true;
                    }
                    con.Close();
                }
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }
            return result;
        }
	
	public static bool DBGetQuestion(string strCaseID, out string[] question) {
            question = new string[1];
			bool result = false;
			// Given the case ID, get the idTypeOfCases from the AvailableCases table. Use this data on the 'FinalChoiceSections' table
			// and the 'SectionNames' column.				
			try{
				int caseID = Convert.ToInt32(strCaseID);
				int idTypesofCases = -1;
				//Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT idTypesOfCases "+
                                      "FROM AvailableCases "+
                                      "WHERE idAvailableCases='" + caseID + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
                    if (rdr.Read() && rdr.HasRows)
                    {
						idTypesofCases =Convert.ToInt32(rdr["idTypesOfCases"].ToString());
                    }
                }
                con.Close();
				
				// Get the final choice questions or the SectionName
				ArrayList arrSecName = new ArrayList();
				con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT SectionName "+
                                      "FROM FinalChoiceSections "+
                                      "WHERE idTypesOfCases='" + idTypesofCases + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);                    
                    if (rdr.HasRows)
                    {
						while (rdr.Read()) {
                            arrSecName.Add(rdr["SectionName"]);
                        }
                    }
                }
                con.Close();
				
				// process the SectionName/Questions
				question = new string[arrSecName.Count];
				if(arrSecName.Count>0){
					result = true;
					for(int i=0; i<arrSecName.Count;i++){
						question[i] = arrSecName[i].ToString();
					}
				}
				
			}
			catch(Exception ex){
				result = false;
				Console.WriteLine(ex.ToString());
			}
			return result;
        }
	
	public static bool GetListAnswers(string idAvailableCases,out string[,] answers) {
            answers = null;
            return GetFinalChoiceAnswerList(idAvailableCases, out answers);            
        }
	
	public static bool GetNumSections(string strCaseID, out int numSections)
        {
            //Set numSections to the number of final decision questions/sections there are in that case
            numSections = 0;
            bool result = false;
			// Given the case ID, get the idTypeOfCases from the AvailableCases table. Use this data on the 'FinalChoiceSections' table
			// and the 'SectionNames'	column.				
			try{
				int caseID = Convert.ToInt32(strCaseID);
				int idTypesofCases = -1;
				//Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT idTypesOfCases "+
                                      "FROM AvailableCases "+
                                      "WHERE idAvailableCases='" + caseID + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
                    if (rdr.Read() && rdr.HasRows)
                    {
						idTypesofCases =Convert.ToInt32(rdr["idTypesOfCases"].ToString());
                    }
                }
                con.Close();
				
				// Get the final choice questions or the SectionName
				ArrayList arrSecName = new ArrayList();
				con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT SectionName "+
                                      "FROM FinalChoiceSections "+
                                      "WHERE idTypesOfCases='" + idTypesofCases + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);                    
                    if (rdr.HasRows)
                    {
						while (rdr.Read()) {
                            arrSecName.Add(rdr["SectionName"]);
                        }
                    }
                }
                con.Close();
				
				// process the SectionName/Questions
				if(arrSecName.Count>0){
					result = true;
					numSections = arrSecName.Count;
				}
				
				// MAY NEED TO ADD SOME CODE HERE AFTER THE DISCUSSION IS COMPLETE
			}
			catch(Exception ex){
				result = false;
				Console.WriteLine(ex.ToString());
			}
			return result;
        }
	
	public static bool GetMaxAnswers(string strCaseID, int numSections, out int[] maxAnswers)
        {
            // Set maxAnswers to the number of final decision answers that can be selected for all questions in that case
            maxAnswers = new int[numSections];
			bool result = false;
			// Given the case ID, get the idTypeOfCases from the AvailableCases table. Use this data on the 'FinalChoiceSections' table
			// and the 'SectionNames'	column.				
			try{
				int caseID = Convert.ToInt32(strCaseID);
				int idTypesofCases = -1;
				//Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT idTypesOfCases "+
                                      "FROM AvailableCases "+
                                      "WHERE idAvailableCases='" + caseID + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);                    
                    if (rdr.Read() && rdr.HasRows)
                    {
						idTypesofCases =Convert.ToInt32(rdr["idTypesOfCases"].ToString());
                    }
                }
                con.Close();
				
				// Get the final choice questions or the SectionName
				ArrayList arrMaxChoices = new ArrayList();
				con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT MaxChoices "+
                                      "FROM FinalChoiceSections "+
                                      "WHERE idTypesOfCases='" + idTypesofCases + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
                    if (rdr.HasRows)
                    {
						while (rdr.Read()) {
                            arrMaxChoices.Add(rdr["MaxChoices"]);
                        }
                    }
                }
                con.Close();
				
				// process the SectionName/Questions
				int i=0;
				if(arrMaxChoices.Count>0){
					if(numSections>=arrMaxChoices.Count){
						for(int ic=0;ic<arrMaxChoices.Count;ic++){
							maxAnswers[i++] = Convert.ToInt32(arrMaxChoices[ic].ToString());
						}
					}
					result = true;
				}
			}
			catch(Exception ex){
				result = false;
				Console.WriteLine(ex.ToString());
			}
			return result;
        }
	
	public static bool GetAnswerValue(string question, string answer, out int value) {
            return GetScoreByQuesAnsValue(question, answer, out value);
        }
	
	public void GetFeedback(List<int> AnswerID, out string[] AnswerFeedback)
        {
           DBGetFeedback(AnswerID, out AnswerFeedback, sectionCounter, InternalComponents.m_strAvailableCaseID);
        }
	
	public static bool DBGetFeedback(List<int> AnswerID, out string[] AnswerFeedback, int sectionNum, string strCaseId)
        {
            //returns the feedback of all the answers given for the current section
			/*
				Incoming looks like below (Assuming there are 4 sections and hence this functions gets called 4 times)
				
				AnswerID[0] = 3				sectionNum = 1
				AnswerID[1] = 4
				
				AnswerID[0] = 1				sectionNum = 2
				AnswerID[1] = 6
				AnswerID[2] = 3
				
				AnswerID[0] = 1				sectionNum = 3
				AnswerID[1] = 4
				
				AnswerID[0] = 2				sectionNum = 4
				
				Output
				------
				When sectionNum = 1
				AnswerFeedback[0] = "blah blah"
				AnswerFeedback[1] = "some more blah blah"
				
				Same logic repeated for rest of the 3 calls (for sectionNum = 2,3 and 4) to this function.
			  */
            AnswerFeedback = null;
			

            try {
				
				// 1. Get Type of Case from case ID
				
				int caseID = Convert.ToInt32(strCaseId);
				int idTypesofCases = -1;
				//Actaul SQL Query
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT idTypesOfCases "+
                                      "FROM AvailableCases "+
                                      "WHERE idAvailableCases='" + caseID + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
                    if (rdr.Read () && rdr.HasRows)
                    {
						idTypesofCases =Convert.ToInt32(rdr["idTypesOfCases"].ToString());
                    }
                }
                con.Close();
				
				// 2. Get the idFinalChoiceSections from FinalChoiceSections table for above case type
				
				int[] numSection;
				getIdFinaChoiceByCaseType(idTypesofCases.ToString(),out numSection);
				
				// 3. Get the 'Actual SectionNumber' that stored in the database
				
				int l_SectionNum = numSection[sectionNum];
				
				
				// 4. Get the required feedbak from the database
                ArrayList arrFb = new ArrayList();				
                con = new SqlConnection();
                //this has to change based on the config file that will be implemented ultimately
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con) {

                    string strQuery = "SELECT Feedback " +
                                      "FROM FinalChoices " +
                                      "WHERE idFinalChoiceSections='" + l_SectionNum + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (rdr.HasRows) {
                        while (rdr.Read()) {
                            arrFb.Add(rdr[0].ToString());
                        }
                    }

                    con.Close();
                }
				
				
				
				// 5. Get the needed feedback based on the answer ID
				AnswerFeedback = new string[arrFb.Count];
				for(int k=0;k<arrFb.Count;k++){
					AnswerFeedback[k] = arrFb[AnswerID[k]].ToString();	
				}							
				
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                return false;
            }
            return true;
        }
	
	private static bool GetFinalChoiceAnswerList(string strAvailableCasesId, out string[,] strAnswerList) {
            bool result = false;
            strAnswerList = null;

            // query to get the choices that are displayed in the final choice screen
            // and the category to which they belong to.
			int caseID = Convert.ToInt32(strAvailableCasesId);
            string sqlCmd = "SELECT finalChoiceAnswers,idFinalChoiceSections "+
                            "FROM FinalChoices "+
                            "WHERE idAvailableCases='" + caseID + "'";
			
            string ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";


            try {
                ArrayList arrAnswerList = new ArrayList();
                ArrayList arrSecId = new ArrayList();
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = ConnectionString;
                con.Open();
                using (con) {
                    SqlCommand cmd = new SqlCommand(sqlCmd, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (rdr.HasRows) {
                        while (rdr.Read()) {
                            arrAnswerList.Add(rdr[0]);
							arrSecId.Add(rdr[1]);
                        }
                        result = true;
                    }
                }
				
				int numOfSections = 1;
				int maxNumOfAnswers = 0;
				int curNumOfAnswers = 0;
				int cur = 0;
				int old = 0;
				for (int cnt = 0; cnt < arrAnswerList.Count; cnt++) {
					cur = Convert.ToInt32(arrSecId[cnt].ToString())-1;
					if(cur != old){
						old = cur;
						numOfSections++;
						curNumOfAnswers = 0;
					}
					curNumOfAnswers++;
					if(curNumOfAnswers > maxNumOfAnswers){
						maxNumOfAnswers = curNumOfAnswers;
					}
				}

                strAnswerList = new string[numOfSections,maxNumOfAnswers];
				int iQn;
				int iQnOld = 0;
				int counter = 0;
                for (int cnt = 0; cnt < arrAnswerList.Count; cnt++) {
					iQn = Convert.ToInt32(arrSecId[cnt].ToString())-1;
					if(iQnOld != iQn){
						iQnOld = iQn;
						counter = 0;
					}
                    strAnswerList[iQn,counter] = arrAnswerList[cnt].ToString();
					counter++;
                }
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }


            return result;
        }
	
	private static bool GetScoreByQuesAnsValue(string inQuestion, string inAnswer, out int value) {
            inQuestion = String.Empty;
            inAnswer = String.Empty;
            value = -1;
            bool result = false;

            string sqlCmd = "SELECT finalChoicePoints"+
                            " FROM FinalChoices"+
                            " WHERE question = @inQuestion AND answer = @inAnswer";
            //this has to change based on the config file that will be implemented ultimately
            string ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";


            try {
                SqlConnection con;
                con = new SqlConnection();
                con.ConnectionString = ConnectionString;
                con.Open();
                using (con) {
                    SqlCommand cmd = new SqlCommand(sqlCmd, con);
                    cmd.Parameters.Add(new SqlParameter("inQuestion", inQuestion));
                    cmd.Parameters.Add(new SqlParameter("inAnswer", inAnswer));
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (rdr.Read () && rdr.HasRows) {
                        value = Convert.ToInt16(rdr["pointsValue"].ToString());
                    }
                }
                result = true;
            }

            catch (Exception ex) {
                Console.WriteLine(ex.Message);
                result = false;
            }

            return result;
        }
	
	public static bool getIdFinaChoiceByCaseType( string idCaseType, out int[] numSection){
			bool result = false;
			numSection = null;
			try{
				int idTypesofCases = Convert.ToInt32(idCaseType);
			   // Get the final choice id - Primary key from FinalChoiceTable
				ArrayList arrIdFinChoice = new ArrayList();
                SqlConnection con;
				con = new SqlConnection();
                con.ConnectionString = "server=128.125.243.240;Initial Catalog=AVP_RCA;User ID=sa;Password=2ndL1fe";
                //con.ConnectionString = ConfigurationManager.AppSettings["AVP_RCAConnectionString"].ToString();

                con.Open();
                using (con)
                {
                    string strQuery = "SELECT idFinalChoiceSections "+
                                      "FROM FinalChoiceSections "+
                                      "WHERE idTypesOfCases='" + idTypesofCases + "'";

                    SqlCommand cmd = new SqlCommand(strQuery, con);
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
                    if (rdr.HasRows){
						while (rdr.Read()) {
                            arrIdFinChoice.Add(rdr["idFinalChoiceSections"]);
                        }
                    }
                }
                con.Close();
				
				// process the SectionName/Questions
				if(arrIdFinChoice.Count>0){
					numSection = new int[arrIdFinChoice.Count];
					for (int i =0;i<arrIdFinChoice.Count;i++){
						numSection[i] = Convert.ToInt32(arrIdFinChoice[i].ToString());
					}					
					result = true;
				}
			}
			catch(Exception ex){
				result = false;
				Console.WriteLine(ex.ToString());
			}
			return result;			
		}
}
